//
//  WHYStatusDAL.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/12/8.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import Foundation

//最大缓存时间
private let maxCacheDataTime: NSTimeInterval = 60 // 60 * 60 * 24 * 7

class WHYStatusDAL {
    
    class func clearDataCache() {
        
        let date = NSDate(timeIntervalSinceNow: -maxCacheDataTime)
        
        let df = NSDateFormatter()
//        指定时区，模拟器可以不用指定，但是真机必须指定。可以随意指定一个，系统会自动调整
        df.locale = NSLocale(localeIdentifier: "en")
        
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let dateStr = df.stringFromDate(date)
        
        let sql = "DELETE FROM T_Status WHERE createdTime < ?;"
        
        WHYSQLiteManeger.sharedManager.queue.inDatabase { (db) -> Void in
            
            if db.executeUpdate(sql, dateStr) {
                
                QL2("删除了\(db.changes())条数据")
                
            }
            
        }
        
    }
    
    class func loadStatus(since_id: Int, max_id: Int, finished: (array: [[String: AnyObject]]?) -> ()) {
        
//       判断是否存在本地缓存
        let array = checkStatusCache(since_id, max_id: max_id)
        
//        存在数据，返回数据
        if array?.count > 0 {
            
            QL2("查询到\(array!.count)条数据")
            finished(array: array)
            
            return
        }
        
        QL2("从网络上加载数据")
        
//        不存在数据，从网络上加载数据
        WHYNetWorkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id) { (result, error) -> () in
            
            if error != nil {
                
                QL4("网络错误")
                
                finished(array: nil)
                return
            }
            
            guard let array = result?["statuses"] as? [[String: AnyObject]] else {
                QL4("数据类型错误")
                finished(array: nil)
                return
            }
        
//        将加载的数据保存到本地
        saveStatusCache(array)
        
//        返回数据
        finished(array: array)
            
        }
    }
    
    private class func checkStatusCache(since_id: Int, max_id: Int) -> [[String: AnyObject]]? {
        
//        QL2("检查本地数据  \(since_id)  \(max_id)")
        
//        加载用户id
        guard let userId = WHYUserAccountViewModel.sharedUserAccount.userAccount?.uid else {
            QL3("用户没有登录")
            return nil
        }
        
//        准备SQL
        var sql = "SELECT statusId, status, userId FROM T_Status\n"
//        规定是哪个用户的数据缓存
        sql += "WHERE userId = \(userId)\n"
//        数据越新，其statusId越大，根据since_id和max_id来判断
        if since_id > 0 {  // 下拉刷新
            sql += "    AND statusId > \(since_id)\n"
        }else if max_id > 0 {  //  上拉刷新
            sql += "    AND statusId < \(max_id)\n"
        }
//        降序排序数据，并规定每次只读取20条数据
        sql += "ORDER BY statusId DESC LIMIT 20;"
        
//        QL2("查询数据 SQL -> \(sql)")
        
        let array = WHYSQLiteManeger.sharedManager.execRecordSet(sql)
        
        var arrM = [[String: AnyObject]]()
        
        for dict in array {
            
            let jsonData = dict["status"] as! NSData
            let result = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
            
            arrM.append(result as! [String : AnyObject])
        }
        
        return arrM
    }
    
    private class func saveStatusCache(array: [[String: AnyObject]]) {
        
//      加载用户id
        guard let userId = WHYUserAccountViewModel.sharedUserAccount.userAccount?.uid else {
            QL3("用户没有登录")
            return
        }
        
        let sql = "INSERT OR REPLACE INTO T_Status (statusId, status, userId) VALUES (?, ?, ?);"
        
        WHYSQLiteManeger.sharedManager.queue.inTransaction { (db, rollBack) -> Void in
            
            for dict in array {
                
                let statusId = dict["id"] as! Int
                
                let json = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                
                if !db.executeUpdate(sql, statusId, json, userId) {
                    QL4("保存数据失败")
                    rollBack.memory = true
                    break
                }
            }
        }
        
        QL2("保存数据成功")
    }
    
}








